#include "StdAfx.h"
#include "YYDNS.h"

#include "Ws2tcpip.h"
#include "Wspiapi.h"
#include "mmsystem.h"

CYYDNS::CYYDNS(void)
{
}


CYYDNS::~CYYDNS(void)
{
}

// This is an example of an exported function.
int CYYDNS::GetDnsRandom(char * cDomainName,char * cIpAddress,size_t IpSize)
{
	struct addrinfo hints, *res; 

	memset(&hints, 0, sizeof(hints)); 
	hints.ai_family=AF_UNSPEC; 
	hints.ai_protocol=IPPROTO_IP   ; 
	hints.ai_socktype=SOCK_STREAM; 
	hints.ai_flags=AI_CANONNAME   ; 

	if (getaddrinfo(cDomainName, NULL, &hints, &res)==0)
	{
		int totalresult=1;
		addrinfo *addritem=res;

		while(addritem->ai_next!=0)
		{
			totalresult++;
			addritem=addritem->ai_next;
		}

		srand( (unsigned)timeGetTime(  ) );
		int selectedaddr=(int)(((double)rand()) / (RAND_MAX + 1) * (totalresult - 0));

		addritem=res;
		for (int i=0;i<selectedaddr;i++)
		{

			addritem=addritem->ai_next;

		}
		memset(cIpAddress,0,IpSize);
		if(getnameinfo(addritem->ai_addr,addritem-> ai_addrlen,cIpAddress,IpSize,NULL,0,NI_NUMERICHOST)==0) 
		{ 
			return 1;
		} 
		else 
		{
			return 0;
		} 


	}
	else
	{
		return 0;

	}

	return 1;
}

int CYYDNS::GetDnsFirstIp(char * cDomainName,char * cIpAddress,size_t IpSize)
{
	struct addrinfo hints, *res; 

	memset(&hints, 0, sizeof(hints)); 
	hints.ai_family=AF_UNSPEC; 
	hints.ai_protocol=IPPROTO_IP   ; 
	hints.ai_socktype=SOCK_STREAM; 
	hints.ai_flags=AI_CANONNAME   ; 

	if (getaddrinfo(cDomainName, NULL, &hints, &res)==0)
	{
		int totalresult=1;
		addrinfo *addritem=res;

		while(addritem->ai_next!=0)
		{
			totalresult++;
			addritem=addritem->ai_next;
		}

// 		srand( (unsigned)timeGetTime(  ) );
// 		int selectedaddr=(int)(((double)rand()) / (RAND_MAX + 1) * (totalresult - 0));
// 
// 		addritem=res;
// 		for (int i=0;i<selectedaddr;i++)
// 		{
// 
// 			addritem=addritem->ai_next;
// 
// 		}
		memset(cIpAddress,0,IpSize);
		if(getnameinfo(addritem->ai_addr,addritem-> ai_addrlen,cIpAddress,IpSize,NULL,0,NI_NUMERICHOST)==0) 
		{ 
			return 1;
		} 
		else 
		{
			return 0;
		} 


	}
	else
	{
		return 0;

	}

	return 1;
}